<?php
/**
 * @since v1.0
 * @modify 2015.6.21
 * @copyright 深圳亿游
 */
require_once(LIB_PATH.'controller/root.con.php');

class remarkCon extends rootCon
{
    public function likeCourseAction(){
        $uid = mylogin::getUid(true);
        $remarkId = r_int('remarkId');
        $key = "likeCourseAction"."$uid-".$remarkId;

        $obj = new RemarkCourse();
        $obj->find($remarkId);

        $likeObj = new RemarkCourseLike();
        $likeObj->uid = $uid;
        $likeObj->remarkId = $remarkId;
        if($likeObj->find()){//取消赞
            $obj->likeCount =  $obj->likeCount-1;
            if($obj->likeCount<0) $obj->likeCount = 0;
            $obj->save();
            $this->updateGetLike($obj->uid,false);
            $this->updateSendLike($uid,false);
            $likeObj->delete();
        }else{//新赞
            $obj->likeCount =  $obj->likeCount+1;
            $this->updateGetLike($obj->uid);
            $this->updateSendLike($uid);
            $obj->save();
            $likeObj->nick = UserExt::getNickByUid($uid);
            $likeObj->status = STATUS_PUBLISH;
            $likeObj->created = date("Y-m-d H:i:s");
            $likeObj->save();
        }

        $this->j(0,"",['likeCount'=>$obj->likeCount]);
    }

   public function likeTeacherAction(){
        $uid = mylogin::getUid(true);
        $remarkId = r_int('remarkId');
        $obj = new RemarkTeacher();
        $obj->find($remarkId);

       $likeObj = new RemarkTeacherLike();
       $likeObj->uid = $uid;
       $likeObj->remarkId = $remarkId;
       if($likeObj->find()){//取消赞
           $obj->likeCount =  $obj->likeCount-1;
           if($obj->likeCount<0) $obj->likeCount = 0;
           $obj->save();
           $this->updateGetLike($obj->uid,false);
           $this->updateSendLike($uid,false);
           $likeObj->delete();
       }else{//新赞
           $obj->likeCount =  $obj->likeCount+1;
           $this->updateGetLike($obj->uid);
           $this->updateSendLike($uid);
           $obj->save();
           $likeObj->nick = UserExt::getNickByUid($uid);
           $likeObj->status = STATUS_PUBLISH;
           $likeObj->created = date("Y-m-d H:i:s");
           $likeObj->save();
       }
       $this->j(0,"",['likeCount'=>$obj->likeCount]);
    }

   public function likeSchoolAction(){
        $uid = mylogin::getUid(true);
        $remarkId = r_int('remarkId');
        $key = "likeSchoolAction"."$uid-".$remarkId;

       $obj = new RemarkSchool();
       $obj->find($remarkId);

       $likeObj = new RemarkSchoolLike();
       $likeObj->uid = $uid;
       $likeObj->remarkId = $remarkId;
       if($likeObj->find()){//取消赞
           $obj->likeCount =  $obj->likeCount-1;
           if($obj->likeCount<0) $obj->likeCount = 0;
           $obj->save();
           $this->updateGetLike($obj->uid,false);
           $this->updateSendLike($uid,false);
           $likeObj->delete();
       }else{//新赞
           $obj->likeCount =  $obj->likeCount+1;
           $this->updateGetLike($obj->uid);
           $this->updateSendLike($uid);
           $obj->save();
           $likeObj->nick = UserExt::getNickByUid($uid);
           $likeObj->status = STATUS_PUBLISH;
           $likeObj->created = date("Y-m-d H:i:s");
           $likeObj->save();
       }

       $this->j(0,"",['likeCount'=>$obj->likeCount]);
    }

    private function updateGetLike($uid,$add=true){
        $user = new User();
        $user->find($uid);
        if($add) {
            $user->getLike = $user->getLike + 1;
        }else{
            $user->getLike = $user->getLike - 1;
        }
        $user->save();
    }

    private function updateSendLike($uid,$add=true){
        $user = new User();
        $user->find($uid);
        if($add){
            $user->sendLike = $user->sendLike+1;
        }else{
            $user->sendLike = $user->sendLike-1;
        }
        $user->save();
    }

    private function updateRemarkCount($uid){
        $user = new User();
        $user->find($uid);
        $user->remarkCount = $user->remarkCount+1;
        $user->save();
    }

    public function saveCourseAction() {
        $uid = mylogin::getUid(true);

        if(!r_int('parentRemarkId')){
            $order = new Order();
            $find = $order->find(r_int('orderId'));
            if(!$find) $this->j(-1,"你没有购买过此课程",['orderId'=>r_int('orderId')]);
            if($order->status != STATUS_BUYER_PAID) $this->j(-2,"订单状态错误",['status'=>$order->status]);
        }


        $obj = new RemarkCourse();
        $obj->load();
        $obj->finalScore = ($obj->schoolScore + $obj->serviceScore + $obj->effectScore)/3;
        $obj->uid = $uid;

        //缓存用户信息
        $user = new User();
        $user->find($uid);
        $obj->nick = $user->nick;
        $obj->avatar = $user->avatar;

        //缓存回复统计
       /* if($obj->parentRemarkId){
            $tmpObj = new RemarkCourse();
            $sql = "SELECT COUNT(1) AS NUM FROM ".$tmpObj->table()." WHERE parentRemarkId=".$obj->parentRemarkId ."";
            $one = $tmpObj->one($sql);
            $replyCount = $one['NUM'];
            $tmpObj->find($obj->parentRemarkId);
            $tmpObj->replyCount = $replyCount;
            $tmpObj->save();
        }*/

        $obj->ip = myrequest::getIP();
        $obj->status = STATUS_PUBLISH;//@todo 删除，目前是先发后审核

        $saved = $obj->save();
        $courseId = $obj->courseId;
        $obj->hide();
        if($saved && !r_int('parentRemarkId')) {
            $order->status = STATUS_BUYER_REMARKED;
            $order->save();
        }

        $imageAll = r('images');
        $i = 0;
        if($imageAll) {
	        foreach($imageAll as $item){
		        $imageFileId = $item;
		        $objImg = new RemarkCourseimg();
		        $objImg->rId = $obj->remarkId;
		        $objImg->imageFileId = $imageFileId;
		        $objImg->find();
		
		        $img = new ImageFile();
		        $img->find($objImg->imageFileId);
		
		        $objImg->sort = $i;
		        $objImg->img = $img->uploadImg;
		        $objImg->status = STATUS_PUBLISH;
		        $objImg->save();
		
		        $i++;
	        }
        }
      

        $this->updateRemarkCount($uid);

        $course = new Course();
        $course->find($courseId);

        $this->updateCourseScore($courseId,r_int('parentRemarkId'));//@todo 先审后发移除

        ScoreExt::add($uid,10,2,"点评",$course->courseName,"pages/classdetail/index?courseId=$courseId",$course->uploadImg);
        $this->j(0,'保存成功',$obj->arr);
    }

    public function updateCourseScore($courseId,$parentRemarkId){
        if(!$parentRemarkId){
            $teacher = new Course();
            $sql = "SELECT COUNT(1) AS NUM,AVG(finalScore) AS avgFinalScore,AVG(effectScore) AS avgEffectScore,AVG(serviceScore) AS avgServiceScore,AVG(schoolScore) AS avgSchoolScore FROM  tbl_remark_course WHERE status=".STATUS_PUBLISH." AND parentRemarkId=0 AND courseId=".$courseId;
            $result = $teacher->getOne($sql);
            $teacher->find($courseId);
            $teacher->totalScore =  round(floatval($result['avgFinalScore']),1);
            $teacher->schoolScore =  round(floatval($result['avgSchoolScore']),1);
            $teacher->effectScore =  round(floatval($result['avgEffectScore']),1);
            $teacher->serviceScore =  round(floatval($result['avgServiceScore']),1);
            $teacher->scoreCount = $result['NUM'];
            $teacher->save();
        }else {//更新父评论的评数量
            $remarkObj = new RemarkCourse();
            $sql = "SELECT COUNT(1) AS NUM  FROM  ".$remarkObj->table()." WHERE status=".STATUS_PUBLISH." AND parentRemarkId=$parentRemarkId ";
            $result = $remarkObj->getOne($sql);
            $remarkObj->find($parentRemarkId);
            $remarkObj->replyCount = $result['NUM'];
            $remarkObj->save();
        }
    }

    public function saveTeacherAction() {
        $uid = mylogin::getUid(true);
        $obj = new RemarkTeacher();
        $obj->load();
        $obj->finalScore = ($obj->schoolScore + $obj->serviceScore + $obj->effectScore)/3;
        $obj->uid = $uid;

        $user = new User();
        $user->find($uid);
        $obj->nick = $user->nick;
        $obj->avatar = $user->avatar;


        //缓存回复统计
        /*        if($obj->parentRemarkId){
            $tmpObj = new RemarkTeacher();
            $sql = "SELECT COUNT(1) AS NUM FROM ".$tmpObj->table()." WHERE parentRemarkId=".$obj->parentRemarkId ."";
            $one = $tmpObj->one($sql);
            $replyCount = $one['NUM'];
            $tmpObj->find($obj->parentRemarkId);
            $tmpObj->replyCount = $replyCount;
            $tmpObj->save();
        }*/

        $obj->ip = myrequest::getIP();
        $obj->status = STATUS_PUBLISH;//@todo 删除，目前是先发后审核
        $obj->save();
        $teacherId = $obj->teacherId;
        $obj->hide();


        $imageAll = r('images');
        if($imageAll) {
	        $i = 0;
	        foreach($imageAll as $item){
		        $imageFileId = $item;
		        $objImg = new RemarkTeacherimg();
		        $objImg->rId = $obj->remarkId;
		        $objImg->imageFileId = $imageFileId;
		        $objImg->find();
		
		        $img = new ImageFile();
		        $img->find($objImg->imageFileId);
		
		        $objImg->sort = $i;
		        $objImg->img = $img->uploadImg;
		        $objImg->status = STATUS_PUBLISH;
		        $objImg->save();
		
		        $i++;
	        }
        }
        

        $this->updateRemarkCount($uid);

        $teacher = new Teacher();
        $teacher->find($teacherId);
        $this->updateTeacherScore($teacherId,$obj->parentRemarkId);//@todo 当评论修改为先审核后发的时候，移除这个

        $urlDesc = $teacher->teacherName;
        $url = "pages/teacherdetail/index?teacherId=$teacherId";
        $img = $teacher->uploadImg;
        ScoreExt::add($uid,10,2,"点评",$urlDesc,$url,$img);
        $this->j(0,'保存成功',$obj->arr);
    }


    private function updateTeacherScore($teacherId,$parentRemarkId){
        //更新老师的评分
        if(!$parentRemarkId){
            $teacher = new Teacher();
            $sql = "SELECT COUNT(1) AS NUM,AVG(finalScore) AS avgFinalScore,AVG(effectScore) AS avgEffectScore,AVG(serviceScore) AS avgServiceScore,AVG(schoolScore) AS avgSchoolScore FROM  tbl_remark_teacher WHERE status=".STATUS_PUBLISH." AND parentRemarkId=0 AND teacherId=".$teacherId;
            $result = $teacher->getOne($sql);

            $teacher->find($teacherId);
            $teacher->finalScore = round(floatval($result['avgFinalScore']),1);
            $teacher->schoolScore = round(floatval($result['avgSchoolScore']),1);
            $teacher->effectScore = round(floatval($result['avgEffectScore']),1);
            $teacher->serviceScore = round(floatval($result['avgServiceScore']),1);
            $teacher->scoreCount = $result['NUM'];
            $teacher->save();
        }else {//更新父评论的评数量
            $remarkObj = new RemarkTeacher();
            $sql = "SELECT COUNT(1) AS NUM  FROM  ".$remarkObj->table()." WHERE status=".STATUS_PUBLISH." AND parentRemarkId=$parentRemarkId ";
            $result = $remarkObj->getOne($sql);
            $remarkObj->find($parentRemarkId);
            $remarkObj->replyCount = $result['NUM'];
            $remarkObj->save();
        }
    }

    public function saveSchoolAction() {
        $uid = mylogin::getUid(true);
        $obj = new RemarkSchool();
        $obj->load();
        $obj->finalScore = ($obj->schoolScore + $obj->serviceScore + $obj->effectScore)/3;
        $obj->uid = $uid;

        $user = new User();
        $user->find($uid);
        $obj->nick = $user->nick;
        $obj->avatar = $user->avatar;

        //缓存回复统计
       /* if($obj->parentRemarkId){
            $tmpObj = new RemarkSchool();
            $sql = "SELECT COUNT(1) AS NUM FROM ".$tmpObj->table()." WHERE parentRemarkId=".$obj->parentRemarkId ."";
            $one = $tmpObj->one($sql);
            $replyCount = $one['NUM'];
            $tmpObj->find($obj->parentRemarkId);
            $tmpObj->replyCount = $replyCount;
            $tmpObj->save();
        }*/

        $obj->ip = myrequest::getIP();
        $obj->status = STATUS_PUBLISH;//@todo 删除，目前是先发后审核
        $obj->save();
        $schoolId = $obj->schoolId;
        $obj->hide();

        $imageAll = r('images');
        if($imageAll) {
	        $i = 0;
	        foreach($imageAll as $item){
		        $imageFileId = $item;
		        $objImg = new RemarkSchoolimg();
		        $objImg->rId = $obj->remarkId;
		        $objImg->imageFileId = $imageFileId;
		        $objImg->find();
		
		        $img = new ImageFile();
		        $img->find($objImg->imageFileId);
		
		        $objImg->sort = $i;
		        $objImg->img = $img->uploadImg;
		        $objImg->status = STATUS_PUBLISH;
		        $objImg->save();
		
		        $i++;
	        }
        }
        


        $this->updateRemarkCount($uid);
        $school = new School();
        $school->find($schoolId);

        $this->updateSchoolScore($schoolId,$obj->parentRemarkId);

        $urlDesc = $school->schoolName;
        $url = "pages/instdetail/index?schoolId=$schoolId";
        $img = $school->logoUrl;
        ScoreExt::add($uid,10,2,"点评",$urlDesc,$url,$img);
        $this->j(0,'保存成功',$obj->arr);
    }

    private function updateSchoolScore($schoolId,$parentRemarkId){
        if(!$parentRemarkId){
            $teacher = new School();
            $sql = "SELECT COUNT(1) AS NUM,AVG(finalScore) AS avgFinalScore,AVG(effectScore) AS avgEffectScore,AVG(serviceScore) AS avgServiceScore,AVG(schoolScore) AS avgSchoolScore FROM  tbl_remark_school WHERE status=".STATUS_PUBLISH." AND parentRemarkId=0 AND schoolId=".$schoolId;
            $result = $teacher->getOne($sql);
            $teacher->find($schoolId);
            $teacher->finalScore = round(floatval($result['avgFinalScore']),1);
            $teacher->schoolScore = round(floatval($result['avgSchoolScore']),1);
            $teacher->effectScore = round(floatval($result['avgEffectScore']),1);
            $teacher->serviceScore =round(floatval($result['avgServiceScore']),1);
            $teacher->scoreCount = $result['NUM'];
            $teacher->save();
        }else {//更新父评论的评数量
            $remarkObj = new RemarkSchool();
            $sql = "SELECT COUNT(1) AS NUM  FROM  ".$remarkObj->table()." WHERE status=".STATUS_PUBLISH." AND parentRemarkId=$parentRemarkId ";
            $result = $remarkObj->getOne($sql);
            $remarkObj->find($parentRemarkId);
            $remarkObj->replyCount = $result['NUM'];
            $remarkObj->save();
        }
    }



    //---课程评价列表------
    public function listCourseAction() {
        $uid = mylogin::getUid(true);
        $obj = new RemarkCourse();
        $sql = "SELECT * FROM ".$obj->table()." WHERE parentRemarkId=0 AND courseId=".r_int('courseId')." AND status=".STATUS_PUBLISH;
        $result = $obj->pager($sql);
        $result['list'] = $this->anonymousList($result['list']);

        $i = 0;
        foreach($result['list'] as $row){
            $objId = $row[$obj->key()];
            $tmpImgObj = new RemarkCourseimg();
            $tmpImgObj->rId = $objId;
            $allImg = $tmpImgObj->all($tmpImgObj->getConByLoad());
            $result['list'][$i]['images'] = $allImg;

            $replay = new RemarkCourse();
            $all = $replay->all([['parentRemarkId',$objId],['status',STATUS_PUBLISH]]);
            $result['list'][$i]['replayList'] = $this->anonymousList($all);

            $remarkId = $result['list'][$i]['remarkId'];
            $remarkLikeObj = new RemarkCourseLike();
            $result['list'][$i]['likeList'] = $this->getLikeList($remarkId,$remarkLikeObj);
            $i++;
        }

        $this->j(0, "列表",$result);
    }

    //---老师评价列表------
    public function listTeacherAction() {
        $uid = mylogin::getUid(true);
        $obj = new RemarkTeacher();
        $sql = "SELECT * FROM ".$obj->table()." WHERE  parentRemarkId=0 AND teacherId=".r_int('teacherId')." AND status=".STATUS_PUBLISH;
        $result = $obj->pager($sql);
        $result['list'] = $this->anonymousList($result['list']);

        $i = 0;
        foreach($result['list'] as $row){
            $objId = $row[$obj->key()];
            $tmpImgObj = new RemarkTeacherimg();
            $tmpImgObj->rId = $objId;
            $allImg = $tmpImgObj->all($tmpImgObj->getConByLoad());
            $result['list'][$i]['images'] = $allImg;

            $replay = new RemarkTeacher();
            $all = $replay->all([['parentRemarkId',$objId],['status',STATUS_PUBLISH]]);
            $result['list'][$i]['replayList'] = $this->anonymousList($all);

            $remarkId = $result['list'][$i]['remarkId'];
            $remarkLikeObj = new RemarkTeacherLike();
            $result['list'][$i]['likeList'] = $this->getLikeList($remarkId,$remarkLikeObj);
            $i++;
        }

        $this->j(0, "列表",$result);
    }

    //---机构评价列表------
    public function listSchoolAction() {
        $uid = mylogin::getUid(true);
        $obj = new RemarkSchool();
        $schoolId = r_int('schoolId');
        $sql = "SELECT * FROM ".$obj->table()." WHERE parentRemarkId=0 AND schoolId=".$schoolId." AND status=".STATUS_PUBLISH;
        $result = $obj->pager($sql);
        $result['list'] = $this->anonymousList($result['list']);

        $i = 0;
        foreach($result['list'] as $row){
            $objId = $row[$obj->key()];
            $tmpImgObj = new RemarkSchoolimg();
            $tmpImgObj->rId = $objId;
            $allImg = $tmpImgObj->all($tmpImgObj->getConByLoad());
            $result['list'][$i]['images'] = $allImg;

            $replay = new RemarkSchool();
            $all = $replay->all([['parentRemarkId',$objId],['status',STATUS_PUBLISH]]);
            $result['list'][$i]['replayList'] = $this->anonymousList($all);


            $teacher = new Teacher();
            $sql = "SELECT * FROM ".$teacher->table()." WHERE schoolId=".$schoolId." AND status=".STATUS_PUBLISH;
            $all = $teacher->query($sql);
            $result['list'][$i]['teacherList'] = $this->anonymousList($all);


            $remarkId = $result['list'][$i]['remarkId'];
            $remarkSchoolLikeObj = new RemarkSchoolLike();
            $result['list'][$i]['likeList'] = $this->getLikeList($remarkId,$remarkSchoolLikeObj);

            $i++;
        }

        $this->j(0, "列表",$result);
    }

    private function getLikeList($remarkId,$remarkLikeObj){
        $remarkLikeObj->status = STATUS_PUBLISH;
        $remarkLikeObj->remarkId = $remarkId;
        $list = $remarkLikeObj->all();
        $nickList = [];
        foreach($list as $item){
            $nickList[] = $item['nick'];
        }

        return $nickList;
    }


    private function anonymousList($list){
        $i = 0;
        foreach($list as $item){
            if($item['anonymous']){
                $list[$i]['uid'] = 0;
                $list[$i]['nick'] = "匿名";
                $list[$i]['avatar'] = FRONT_URL.'/default.png';
            }else{
                $list[$i]['avatar'] = FRONT_URL.$list[$i]['avatar'];
            }
            $i++;
        }
        return $list;
    }
}



